package demo.db.redis;

import java.util.concurrent.TimeUnit;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import io.lettuce.core.RedisClient;

/**
 * Redis锁
 *
 */
public class RedisLockDemo {

    public static StringRedisTemplate template = RedisTemplateUtils.buildStringRedisTemplate(RedisTemplateDemo.FACTORY);

    public static ValueOperations<String, String> opsForValue = template.opsForValue();

    RedisClient redisClient = LettuceDemo.buildRedisClient();

    public boolean lock(String key) {
        return opsForValue.setIfAbsent(key, String.valueOf(Thread.currentThread().getId()));
    }

    
    public boolean lock(String key, int seconds) {
        return opsForValue.setIfAbsent(key, String.valueOf(Thread.currentThread().getId()), seconds, TimeUnit.SECONDS);
    }

    public void unLock(String key) {
        template.delete(key);
    }
}
